<?php

namespace app\admin\controller;

use app\admin\model\Villages;
use app\admin\model\Area;

use think\Db;
use think\Exception;
use think\Request;

class Memberauth extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        switch ($this->admin->type) {
            case 0:
                $this->defaultWhere = ['b.isDelete' => ['neq', 1]];
                break;
            case 1:
                $this->defaultWhere = ['b.cityId' => $this->admin->cityId, 'b.isDelete' => ['neq', 1]];
                break;
            case 2:
                $this->defaultWhere = ['b.xianId' => $this->admin->xianId, 'b.isDelete' => ['neq', 1]];
                break;
            case 3:
            case 6:
                $this->defaultWhere = ['b.townId' => $this->admin->townId, 'b.isDelete' => ['neq', 1]];
                break;
            case 4:
                $this->defaultWhere = ['b.villageId' => $this->admin->villageId, 'b.isDelete' => ['neq', 1]];
                break;
            default:
                $this->defaultWhere = ['b.isDelete' => ['neq', 1]];
                break;
        }
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($where, $this->defaultWhere);
            }

            $join = [
                ['__MEMBER__ b', 'b.id = a.memberId']
            ];
            $field = 'a.id, a.authType, a.checkStatus, a.createDate, a.memberId, b.name, b.mobile, b.identityNumber, b.cityId, b.xianId, b.townId, b.villageId';
            $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
            $count = $model->alias('a')->where($where)->join($join)->count();
            if ($list) {
                foreach ($list as $item) {
                    // 所在地
                    $item['area'] = getArea($item);
                }
            }

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return $this->fetch('member/auth_list', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'param' => $request->param()
        ]);
    }

    /**
     * 审核 通过/不通过 操作
     */
    public function checkHandle(Request $request){
        $model = model($this->model);
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $param = $request->param();
                $member = \app\admin\model\Member::get($param['memberId']);

                if(!$member){
                    Db::rollback();
                    return $this->error('该村民不存在！');
                }

                if ($param['value'] == 1) {
                    // 通过
                    $result = $model->where('id', $param['id'])->update(['checkStatus' => 1]);
                    if ($result === false) {
                        Db::rollback();
                        return $this->error('操作失败');
                    }

                    if ($member->isDelete == 1) {
                        $member->isDelete = 2;
                    }
                    if ($param['authType'] == 1) {
                        $member->checkPersonal = 1;
                    } else {
                        $member->checkManage = 1;
                    }
                    $resMember = $member->save();
                    if ($resMember === false) {
                        Db::rollback();
                        return $this->error('操作失败！');
                    }

                    $user = \app\admin\model\User::get($member->userId);
                    if (!$user) {
                        Db::rollback();
                        return $this->error('用户不存在！');
                    }
                    $user->memberId = $member->id;
                    $user->save();

                    Db::commit();
                    return $this->success('操作成功！');
                } else {
                    // 不通过
                    $result = $model->where('id', $param['id'])->update(['checkStatus' => 3, 'failMsg' => $param['failMsg']]);
                    if ($result === false) {
                        Db::rollback();
                        return $this->error('操作失败');
                    }

                    if ($param['authType'] == 1) {
                        $member->checkPersonal = 3;
                        $member->personalFailMsg = $param['failMsg'];
                    } else {
                        $member->checkManage = 3;
                        $member->manageFailMsg = $param['failMsg'];
                    }
                    $resMember = $member->save();
                    if ($resMember === false) {
                        Db::rollback();
                        return $this->error('操作失败！');
                    }

                    Db::commit();
                    return $this->success('操作成功！');
                }
            } catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['cityId']) && $filter['cityId']){
                $where['b.cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['b.xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['b.townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['b.villageId'] = $filter['villageId'];
            }

            if(isset($filter['authType']) && $filter['authType']){
                $where['a.authType'] = $filter['authType'];
            }
            if(isset($filter['checkStatus']) && $filter['checkStatus']){
                $where['a.checkStatus'] = $filter['checkStatus'];
            }
            if(isset($filter['mobile']) && $filter['mobile']){
                $where['b.mobile'] = ['like', '%'.$filter['mobile'].'%'];
            }
        }

        return $where;
    }

}